import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */

    public ArrayList<Integer> getPath (TreeNode root, int target) {
        ArrayList<Integer> ret = new ArrayList<>();
        TreeNode node = root;
        while (node.val != target) {
            ret.add(node.val);
            if (node.val < target)
                node = node.right;
            else
                node = node.left;
        }
        ret.add(node.val);
        return ret;
    }

    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
        // 递归
        /*
        if (q < p) {
            int temp = q;
            q = p;
            p = temp;
        }

        if (p <= root.val && q >= root .val)
            return root.val;
        else if (p > root.val) 
            return lowestCommonAncestor(root.right, p, q);
        else 
            return lowestCommonAncestor(root.left, p, q);
        */

        // 搜索路径比较
        ArrayList<Integer> arr1 = getPath(root, p);
        ArrayList<Integer> arr2 = getPath(root, q);

        int ret = 0;
        for (int i = 0; i < arr1.size() && i < arr2.size(); i++) {
            int num1 = arr1.get(i);
            int num2 = arr2.get(i);
            if (arr1.get(i).intValue() == arr2.get(i).intValue())
                ret = arr1.get(i);
            else 
                break;
        }

        return ret;
    }
}